/**
 * Copyright (C) T-Systems International, 2013-2014
 *
 * The copyright of the computer program herein is the property of
 * T-Systems International. The program may be used and/or copied
 * only with the written permission of T-Systems International or in
 * accordance with the terms and conditions stipulated in the
 * agreement/contract under which the program has been supplied.
 *
 * $Author$
 * $Date$
 * $Rev$
 */
package com.tsystems.migdb.batch.listener;

import com.tsystems.migdb.batch.Person;
import com.tsystems.migdb.batch.utils.MigdbToStringBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.batch.core.ChunkListener;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.ResultSet;
import java.util.List;

@Log4j2
@AllArgsConstructor
public class MigdbChunkListener implements ChunkListener {

    private final JdbcTemplate template;
    private final String query;

    @Override
    public void beforeChunk(ChunkContext context) {
        log.debug("starting a chunk");
        log.debug(MigdbToStringBuilder.toString(context.getStepContext().getStepExecution()));
    }

    @Override
    public void afterChunk(ChunkContext context) {
        log.debug("chunk has been finished");
        printDatabaseContents();
    }

    @Override
    public void afterChunkError(ChunkContext context) {
        log.error("chunk has been failed");
        printDatabaseContents();
    }

    protected void printDatabaseContents() {
        List<Person> results = template.query(query,
                (ResultSet rs, int rowNum) -> new Person(rs.getString(1), rs.getString(2)));
        log.debug("Database contents:\n" + StringUtils.join(results, "\n"));
    }

}